package se.hh.lab.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import se.hh.lab.dao.DaoException;
import se.hh.lab.dao.UserProvisionalBorrowDao;
import se.hh.lab.domain.Provisional;
import se.hh.lab.jdbc.JdbcUtil;

public class UserProvisionalBorrowDaoImpl implements UserProvisionalBorrowDao
{

	@SuppressWarnings("finally")
	@Override
	public int updateProvisional(Provisional pro) 
	{
		Connection con=null;
		ResultSet rs=null;
		PreparedStatement ps=null;
		int mark=0;
		try
		{
			con=JdbcUtil.getConnection();
			String sql="Update lab_provisional set context=? where userID=?";
			ps=con.prepareStatement(sql);
			ps.setString(1, pro.getContext());
			ps.setString(2, pro.getUserID());	
		    mark=ps.executeUpdate();
			
		}
		catch(Exception e)
		{
			throw new DaoException(e.getMessage(),e);
		}
		finally
		{
			try
			{
				JdbcUtil.free(rs, ps, con);
			}
			catch (SQLException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return mark;
		}
	}

	@SuppressWarnings("finally")
	@Override
	public int deleteProvisional(Provisional pro) 
	{
		Connection con=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		int mark=0;
		try
		{
			con=JdbcUtil.getConnection();
			String sql="delete from lab_provisional where userID=?";
			ps=con.prepareStatement(sql);
			ps.setString(1, pro.getUserID());
			mark=ps.executeUpdate();			
		}
		catch(Exception e)
		{
			throw new DaoException(e.getMessage(), e);
		}
		finally
		{
			try
			{
				JdbcUtil.free(rs, ps, con);
			}
			catch (SQLException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return mark;
		}
		
	}

	@SuppressWarnings("finally")
	@Override
	public Provisional getProvisional(Provisional pro) 
	{
		Connection con=null;
		PreparedStatement ps=null;
		ResultSet rs=null;		
		try
		{
			
			con=JdbcUtil.getConnection();
			String sql="select *from lab_provisional where userID=?";
			ps=con.prepareStatement(sql);
			ps.setString(1, pro.getUserID());
			rs=ps.executeQuery();
			
			while(rs.next())
			{
				pro=new Provisional();
				pro.setContext(rs.getString("context"));	
				pro.setUserID(rs.getString("userID"));
			}
		
		}
		catch(Exception e)
		{
			throw new DaoException(e.getMessage(),e);
		}
		finally
		{
			try
			{
				JdbcUtil.free(rs, ps, con);
			}
			catch (SQLException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
			return pro;
		}		
		
	}

}
